<template>
    <div class="add_contact ">
        <DefaultHeader></DefaultHeader>
        <div class="add_contact_panel">
            <div>
                <HeaderSearchInput v-model="searchInput" @keydown.enter.prevent="searchHandle"></HeaderSearchInput>
                <div class="tip">
                    按下enter触发搜索功能~
                </div>
            </div>
            <!-- 被搜索出的用户展示 -->
            <div class="search_user_container no_scroll_bar">
                <UserItem v-for="(item, index) in users" :key="index" :user="item">
                    <template #action>
                        <div>
                            <el-button @click="friendRequestHandle(item)">添加</el-button>
                        </div>
                    </template>
                </UserItem>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { friendRequest } from '@/api/friendRequest';
import { searchApi } from '@/api/user';
import DefaultHeader from '@/components/header/DefaultHeader.vue';
import HeaderSearchInput from '@/components/search_input/HeaderSearchInput.vue';
import UserItem, { type FriendRequestItem } from '@/components/UserItem.vue';
import { ElMessage } from 'element-plus';
import { ref } from 'vue';

const searchInput = ref();

const users = ref<Array<FriendRequestItem>>([
    { userId: 1, nick: '范小勤', avatar: 'https://picsum.photos/id/1012/200/200' },
    { userId: 2, nick: '蔡徐坤', avatar: 'https://picsum.photos/id/1025/200/200' },
]);

const friendRequestHandle = async (item: FriendRequestItem) => {
    try {
        const result = await friendRequest({ receiveId: item.userId, remark: "你好,我想认识一下你" });
        if (result.code === 1) {
            ElMessage.success("添加成功");
        } else {
            ElMessage.error(result.msg);
        }
    } catch (e) {
        console.log(e);
    }
}

const searchHandle = async () => {
    try {
        const result = await searchApi(searchInput.value);
        if (result.code === 1) {
            users.value = result.data;
        }
    }
    catch (e) {
        console.log(e);
    }
}

</script>

<style lang="scss" scoped>
.add_contact {
    flex: 1;
    display: flex;
    flex-flow: column;

    .add_contact_panel {
        flex: 1;
        display: block;

        .search_user_container {
            height: 680px;
            overflow-y: auto;
            overscroll-behavior: contain;
        }
    }
}

.tip {
    padding: 5px;
    font-size: 10px;
    opacity: 0.8;
    text-align: end;
}
</style>
